/**
 * @name: picker分级选择器
 * @version: v1.0.0
 */
;layui.define(['methods'], function (exports) {
    var o = layui.jquery,
        ly = layui.layer,
        u = layui.util,
        methods = layui.methods,
        css = '',
        index,
        mainHtml = '',
        pid = 0,
        deep = 0,
        areaDom = null,
        resultDom = null,
        elem = null,
        saDom = null,
        mixed = null,
        defaultResult = [],
        result = [],
        _this = null,
        callback = null;

    var pickerPower = {
        render: function (data, cb) {
            if (typeof cb !== 'function') return console.error('未配置回调函数')
            if (typeof data !== 'object') return console.error('传参错误')
            if (!data.hasOwnProperty('elem')) return console.error('请配置容器class值[elem]')
            if (!data.hasOwnProperty('url')) return console.error('请配置url')
            _this = this;
            mixed = data;
            callback = cb;
            mixed.deep = mixed.deep || 3;
            mixed.title = mixed.title || '请选择';
            mixed.radius = !(data.hasOwnProperty('radius') && !mixed.radius);
            elem = o('.' + mixed.elem);
            saDom = mixed.elem + 'SelectArea' + elem.index();
            defaultResult = !result.length ? mixed.value || [] : result;
            mainHtml = '';
            _this.init();
        },
        init: function () {
            _this.buildCss();
            _this.buildHtml();
            _this.getData();
            _this.openPopup();
        },
        buildCss: function () {
            var height = mixed.height || '80vh';
            css += '.' + mixed.elem + '{display: none}';
            css += ".render-picker {display: flex; flex-direction: column;background-color: #fff; padding: .3rem .3rem 0 .3rem; height: " + height + "; overflow: hidden; } .render-picker .title { text-align: center; margin-bottom: .2rem; font-size: var(--default-font-size-28); font-weight: bold; } .render-picker .select-title { font-size: var(--default-font-size-28); font-weight: bold; padding: .2rem 0; } .render-picker .result { display: flex; align-items: center; flex-wrap: wrap; } .render-picker .result .item { margin: .2rem 0; display: flex; align-items: center; justify-content: center; } .render-picker .result .val { border-radius: .1rem; padding: .15rem; background-color: #eee; font-size: .24rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .render-picker .result .lay-this .val { color: var(--bd); border: 1px solid var(--bd); background-color: #fff !important; } .render-picker .result .item:after { content: '-'; margin: 0 .1rem; } .render-picker .result .item:last-child:after { content: ''; } .render-picker .select-area { flex:1; overflow: auto; } .render-picker .select-area .item { padding: .2rem; font-size: var(--default-font-size-26); } .render-picker .select-area .lay-this { color: var(--bd); }";
            !o('#pickerCss').length ? o('head').append('<style id="pickerCss">' + css + '</style>') : '';
        },
        buildHtml: function () {
            mainHtml += '<div class="render-picker">';
            mainHtml += '<div class="title">' + mixed.title + '</div>';
            mainHtml += '<div class="result"></div>';
            mainHtml += '<div class="select-title">请选择</div>';
            mainHtml += '<div class="select-area" id="' + saDom + '"></div>';
            mainHtml += '</div>';
            elem.html(mainHtml);
            areaDom = elem.find('.select-area');
            resultDom = elem.find('.result');
        },
        getData: function () {
            var html = '';
            if (defaultResult.length > 0) {
                pid = defaultResult.length === 1 ? 0 : defaultResult[defaultResult.length - 2].id;
                deep = defaultResult.length - 1;

                defaultResult.forEach(function (v, k) {
                    var pid = !k ? 0 : defaultResult[k - 1].id;
                    var act = k === defaultResult.length - 1 ? 'lay-this' : '';
                    resultDom.append('<div data-pid="' + pid + '" data-id="' + v.id + '" lay-pickerPower="topChange" class="item ' + act + '"><div class="val">' + v.value + '</div></div>');
                })

                result = defaultResult;
                defaultResult = [];
            }
            methods.fetchGet(mixed.url, {pid: pid, deep: deep}, function (d) {
                if (d.code === 1) {
                    d.data.forEach(function (v, k) {
                        html += '<div lay-pickerPower="change" data-pid="' + pid + '" data-id="' + v.id + '" class="item">' + v.title + '</div>';
                    })
                    areaDom.html(html);
                    _this.scrollTo();
                }
            })
        },
        scrollTo: function () {
            if (result[deep]) {
                var items = areaDom.find('.item');
                var selectArea = document.getElementById(saDom);
                var containerHeight = selectArea.offsetHeight;
                var itemToScrollTo = null;
                for (var i = 0; i < items.length; i++) {
                    if (items[i].textContent.trim() === result[deep].value) {
                        itemToScrollTo = items[i];
                        items.eq(i).addClass('lay-this')
                        break;
                    }
                }
                if (itemToScrollTo) {
                    var itemHeight = itemToScrollTo.offsetHeight;
                    var itemTop = itemToScrollTo.offsetTop;
                    var scrollTarget = itemTop - ((containerHeight - itemHeight) / 2);
                    if (scrollTarget < 0) {
                        scrollTarget = 0;
                    } else if (scrollTarget + containerHeight > selectArea.scrollHeight) {
                        scrollTarget = selectArea.scrollHeight - containerHeight;
                    }
                    selectArea.scrollTop = scrollTarget;
                }
            }
        },
        eventListen: function () {
            u.on('lay-pickerPower', {
                change: function () {
                    var id = o(this).attr('data-id'), nextPid = o(this).attr('data-pid'), text = o(this).text();
                    o(this).addClass('lay-this').siblings().removeClass('lay-this');
                    if (resultDom.find('.item')[deep]) {
                        resultDom.find('.item').eq(deep).find('.val').html(text);
                    } else {
                        resultDom.find('.item').removeClass('lay-this');
                        resultDom.append('<div data-pid="' + nextPid + '" data-id="' + id + '" lay-pickerPower="topChange" class="item lay-this"><div class="val">' + text + '</div></div>');
                    }
                    result[deep] = {id: id, value: text}
                    pid = id;
                    deep = resultDom.find('.lay-this').index() + 1;
                    mixed.deep === deep ? _this.closePopup() : _this.getData();
                },
                topChange: function () {
                    var nextPid = o(this).attr('data-pid');
                    o(this).addClass('lay-this').siblings().removeClass('lay-this');
                    pid = nextPid;
                    deep = o(this).index();
                    resultDom.find('.item').each(function (i, v) {
                        if (i > deep) {
                            result.splice(i, 1);
                            o(this).remove();
                        }
                    })
                    _this.getData();
                }
            })
        },
        openPopup: function () {
            index = ly.open({
                type: 1,
                offset: 'b',
                anim: 'slideUp',
                area: ['100%', elem.height() + 'px'],
                title: false,
                closeBtn: 0,
                shade: 0.3,
                shadeClose: true,
                content: elem,
                success: function (layero, index, that) {
                    if (mixed.radius) {
                        elem.parents('.layui-layer-page').css('border-radius', '0.2rem 0.2rem 0 0');
                        elem.parents('.layui-layer-content').css('border-radius', '0.2rem 0.2rem 0 0').css('overflow', 'hidden');
                    }
                    _this.eventListen();
                },
                end: function () {
                    if(result.length !== mixed.deep){
                        result = [];
                        pid = 0;
                        deep = 0;
                    }
                    callback(result);
                }
            });
        },
        closePopup: function () {
            ly.close(index);
        }
    }

    exports('pickerPower', pickerPower);
});
